﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace PokemonBattle.PokemonData.Util
{
    public static class DataStreamHelper
    {
        public static T FromStream<T>(Stream input) where T : DataStream
        {
            var obj = Activator.CreateInstance<T>();
            obj.Load(input);
            return obj;
        }

        public static List<T> ReadList<T>(BinaryReader reader) where T : DataStream
        {
            int count = reader.ReadInt32();
            var list = new List<T>(count);
            for (int i = 0; i < count; i++)
            {
                var item = FromStream<T>(reader.BaseStream);
                list.Add(item);
            }
            return list;
        }

        public static void WriteList<T>(this List<T> list, BinaryWriter writer) where T : DataStream
        {
            writer.Write(list.Count);
            foreach (T item in list)
            {
                item.Save(writer.BaseStream);
            }
        }

        public static T FromFile<T>(string path) where T : DataStream
        {
            T data = null;
            using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                data = FromStream<T>(stream);
                stream.Close();
            }
            return data;
        }

        public static void SaveFile(this DataStream data, string path)
        {
            using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                data.Save(stream);
                stream.Flush();
                stream.Close();
            }
        }
    }
}